package dormouse.fx.metadata;

import java.io.IOException;
import java.net.URL;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.biogroovy.eutils.PubMedArticleReader;
import org.biogroovy.models.Article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dormouse.vfs.event.IFileSelectionEvent;
import dormouse.vfs.metadata.IMetadataViewer;
import dormouse.vfs.ui.renderers.IFileRenderer;

/**
 * This component is responsible for displaying PDF metadata.
 */
public class PDFMetadataRenderer implements IMetadataViewer<Node> {
	
	/** Class logger. */
	private static final Logger log = LoggerFactory.getLogger(PDFMetadataRenderer.class);
	
	private PDFPanelController controller;
	private AnchorPane panel;
	
	private static final String[] EXTS = new String[]{"pdf"};
	
	/**
	 * Constructor.
	 */
	public PDFMetadataRenderer(){
		init();
	}

	@Override
	public void preview(FileObject file) {
		bindFile(file);
	}

	@Override
	public IFileRenderer<Node> getPreviewComponent(FileObject file) {
		bindFile(file);
		return null;
	}

	@Override
	public Node getComponent() {
		return panel;
	}

	@Override
	public void fileSelected(IFileSelectionEvent event) {
		FileObject file = event.getSelectedFile();
		bindFile(file);
	}
	
	private void bindFile(FileObject file){
		PubMedArticleReader reader = new PubMedArticleReader();
		try {
			Article article = reader.read(file.getContent().getInputStream());
			controller.bind(article);
		} catch (FileSystemException e) {
			log.error(e.getMessage(), e);
		}
		
	}

	
	private void init() {
		
		 	URL url = getClass().getResource("/PDFMetadataPanel.fxml");
	        FXMLLoader loader = new FXMLLoader(url);

	        try {
	            panel = (AnchorPane) loader.load();
	            controller = (PDFPanelController) loader.getController();            

	        } catch (IOException ex) {
	            log.error(ex.getMessage(), ex);
	        }
		
	}

	@Override
	public String[] getExtensions() {
		return EXTS;
	}

}
